/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

var app = __webpack_require__(1);
var managerCtrl = __webpack_require__(2)(app);
var merchantCtrl = __webpack_require__(3)(app);
var foodCtrl = __webpack_require__(4)(app);
var navCtrl = __webpack_require__(5)(app);
var orderCtrl = __webpack_require__(6)(app);

/***/ }),
/* 1 */
/***/ (function(module, exports) {

var app = angular.module('managerApp', ['ngRoute', 'ui.bootstrap', 'angularFileUpload', 'ngWebSocket']);
// app.controller('foodCtrl', function ($scope, $route) { $scope.$route = $route; });
// app.controller('orderCtrl', function ($scope, $route) { $scope.$route = $route; });

var socket;
if (!socket) {
    socket = io.connect('http://localhost:3001');
}
var updateFunc = function () {
    console.log('no binding..');
};
var getUpdateFunc = function (data) {
    updateFunc(data);
};
socket.on('update', getUpdateFunc);

app.config(function ($routeProvider) {
    $routeProvider.when('/food', {
        templateUrl: 'food.html',
        controller: 'foodCtrl'
    }).when('/order', {
        templateUrl: 'order.html',
        controller: 'orderCtrl'
    }).otherwise({
        redirectTo: '/food'
    });
});

app.factory('socketio', function () {
    var methods = {
        getSocket: function () {
            return socket;
        },
        setFunc: function (func) {
            updateFunc = func;
        }
    };
    return methods;
});

module.exports = app;

/***/ }),
/* 2 */
/***/ (function(module, exports) {

module.exports = function (app) {
    app.controller('managerCtrl', function ($scope, $rootScope) {

        // $rootScope.types
        // $rootScrop.Merchant
        // $rootScrop.search
    });
};

/***/ }),
/* 3 */
/***/ (function(module, exports) {

module.exports = function (app) {
    app.controller('merchantCtrl', function ($scope, $rootScope, $http, $interval, socketio) {

        $scope.initMerchant = function () {
            console.log("call merchant init()", $rootScope.merchant);
            // $scope.mockLogin(); // 仅测试时�
            // $interval(function () {
            //     console.log("wait 1s");
            $http({
                method: 'GET',
                url: 'merchant/currentUser'
            }).then(function successCallBack(res) {
                console.log('callback merchant initMerchant() success', res);
                // $scope.merchant = res.data.data;
                $rootScope.merchant = res.data.data;
                socketio.getSocket().emit('id', { id: $rootScope.merchant._id });
                console.log('callback merchant initMerchant() success', $rootScope.merchant);
            }, function errCallback(res) {
                console.log('callback merchant initMerchant() error', res);
            });
            // }, 1000, 1);    
        };

        $scope.logout = function () {
            console.log("call logout");
            $http({
                method: 'GET',
                url: 'api/merchant/login/logout'
            });
            window.location.href = 'index.html';
        };

        $scope.mockLogin = function () {
            console.log("call merchant mock login()");
            $http({
                method: 'POST',
                url: 'api/merchant/login',
                data: { name: 'max', password: 'qwerdf' }
            }).then(function successCallBack(res) {
                console.log('callback merchant mock login() success', res);
            }, function errCallback(res) {
                console.log('callback merchant mock login() error', res);
            });
        };
    });
};

/***/ }),
/* 4 */
/***/ (function(module, exports) {

module.exports = function (app) {
    app.controller('foodCtrl', function ($scope, $rootScope, $http, $modal, $interval) {

        window.updateFunc = function () {};

        $scope.orderByX = function (x) {
            console.log("call order by", x);
            $scope.orderBy = x;
        };
        $scope.filter = function () {
            console.log("call filter");
            $scope.search = $rootScope.search;
        };

        // 初始化，依赖�Merchant Ctrl
        $scope.init = function () {
            console.log("call food init()");

            $scope.types(); // 初始�Food Types

            $scope.merchant = $rootScope.merchant; // rootScope �Merchant 来自�Merchant Ctrl
            // if ($scope.merchant != undefined && $scope.merchant._id != undefined) {
            console.log('merchant', $scope.merchant);
            $scope.sync(); // 刷新菜品信息
            // } else {
            // console.log('wait 2s');
            // $interval(function () {
            //     console.log('sync after 2s');
            //     $scope.merchant = $rootScope.merchant;
            //     if ($scope.merchant != undefined && $scope.merchant._id != undefined) {
            //         console.log('merchant', $scope.merchant)
            //         $scope.sync();   // 刷新菜品信息
            //     }
            // }, 2000, 1);
            // }
        };

        // 初始�Food Types
        $scope.types = function () {
            console.log("call food foodtype()");
            $http({
                method: 'GET',
                url: 'foodtype'
            }).then(function successCallBack(res) {
                console.log('callback food foodtype() success', res);
                $rootScope.types = res.data.data;
            }, function errCallback(res) {
                console.log('callback food foodtype() error', res);
            });
        };

        $scope.typeId2Name = function (id) {
            for (var i = 0; i < $rootScope.types.length; i++) {
                if (id == $rootScope.types[i]._id) {
                    return $rootScope.types[i].typeName;
                }
            }
        };

        // 同步菜品信息依赖 Merchant ID
        $scope.sync = function () {
            console.log("call food sync()");
            $http({
                method: 'GET',
                url: 'foods/byM'
            }).then(function successCallBack(res) {
                console.log('callback sync() success', res);
                $scope.foods = res.data.data;
                // Food Type: ID -> Name
                for (var i = 0; i < $scope.foods.length; i++) {
                    $scope.foods[i].foodType = $scope.typeId2Name($scope.foods[i].foodType);
                }
            }, function errCallback(res) {
                console.log('callback sync() error', res);
            });
        };

        // 呼出模态框
        $scope.add = function () {
            console.log("call add()");
            $scope.openAddModal();
        };

        // 呼出模态框，并自动填表
        $scope.edit = function (x) {
            console.log("call edit(", x, ")");
            // TODO 要改为在前端本地查找
            $http({
                method: 'GET',
                url: 'foods/' + x
            }).then(function successCallBack(res) {
                // 请求成功将数据插入模态框
                console.log('callback edit() success', res);
                $scope.openUpdModal(res.data.data);
            }, function errCallback(res) {
                console.log('callback edit() error', res);
            });
        };

        $scope.delete = function (x) {
            console.log("call delete(", x, ")");
            $http({
                method: 'DELETE',
                url: 'foods/' + x
            }).then(function successCallBack(res) {
                console.log('callback delete() success', res);
                $scope.sync();
            }, function errCallback(res) {
                console.log('callback delete() error', res);
            });
        };

        $scope.openAddModal = function () {
            var modalInstance = $modal.open({
                templateUrl: 'modal.html',
                controller: 'addModalCtrl',
                resolve: {
                    method: function () {
                        return $scope.sync;
                    },
                    data: function () {
                        // return $scope.merchant;
                        return $rootScope.merchant;
                    }
                }
            });
        };

        $scope.openUpdModal = function (data) {
            var modalInstance = $modal.open({
                templateUrl: 'modal.html',
                controller: 'updModalCtrl',
                resolve: {
                    method: function () {
                        return $scope.sync;
                    },
                    data: function () {
                        return data;
                    }
                }
            });
        };
    });

    //模态框对应的Controller
    app.controller('addModalCtrl', function ($scope, $rootScope, $modalInstance, $http, method, data, FileUploader) {

        $scope.food = {};
        $scope.hide = true;

        $scope.init = function () {
            $scope.title = '新增菜品';
            $scope.method = method;
            $scope.types = $rootScope.types;
        };

        $scope.submit = function () {
            $scope.food.merchant = data._id;
            console.log("call add modal submit()", $scope.food);
            if ($scope.validateCompletion()) {
                $http({
                    method: 'POST',
                    url: 'foods',
                    data: $scope.food
                }).then(function successCallBack(res) {
                    console.log('callback add modal submit() success', res);
                    $scope.method();
                    $modalInstance.close();
                }, function errCallback(res) {
                    console.log('callback add modal submit() error', res);
                    alert("submit fail");
                });
            }
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };

        // warnning using DOM
        $scope.browse = function () {
            document.getElementById('file').click();
        };

        /* 上传图片 */
        // 上传控件
        $scope.uploader = new FileUploader({
            url: '/api/upload/foodpic',
            removeAfterUpload: true,
            queueLimit: 1
        });

        // 提交上传
        $scope.upload = function () {
            console.log("call upload");
            $scope.uploader.uploadAll();
        };

        // 上传完成执行此方�
        $scope.uploader.onCompleteItem = function (item, response, status, headers) {
            console.log("callback upload", response.path);
            $scope.food.foodPic = response.path;
            $scope.hide = false;
            alert("上传成功");
            $scope.validate.div.foodPic = '';
            $scope.validate.help.foodPic = '';
        };
        /* 上传图片 END*/

        /* 前端校验 */
        $scope.validate = {
            class: {
                success: 'has-success has-feedback',
                warnning: 'has-warning has-feedback',
                error: 'has-error has-feedback',
                successGlyphicon: 'glyphicon glyphicon-ok form-control-feedback',
                warningGlyphicon: 'glyphicon glyphicon-warning-sign form-control-feedback',
                errorGlyphicon: 'glyphicon glyphicon-remove form-control-feedback'
            },
            div: {},
            span: {},
            help: {}
        };

        $scope.validateCompletion = function () {
            var validate = true;
            if ($scope.food.foodName == undefined || $scope.food.foodName == '') {
                $scope.validate.div.foodName = $scope.validate.class.error;
                $scope.validate.span.foodName = $scope.validate.class.errorGlyphicon;
                $scope.validate.help.foodName = '菜品名称不能为空';
                validate = false;
            }
            if ($scope.food.foodPrice == undefined || $scope.food.foodPrice == '') {
                $scope.validate.div.foodPrice = $scope.validate.class.error;
                $scope.validate.span.foodPrice = $scope.validate.class.errorGlyphicon;
                $scope.validate.help.foodPrice = '菜品价格不能为空';
                validate = false;
            }
            if ($scope.food.foodPic == undefined || $scope.food.foodPic == '') {
                $scope.validate.div.foodPic = $scope.validate.class.error;
                $scope.validate.help.foodPic = '请上传图片';
                validate = false;
            }
            if ($scope.food.foodType == undefined || $scope.food.foodPic == '') {
                $scope.validate.div.foodType = $scope.validate.class.error;
                $scope.validate.help.foodType = '请选择菜品类型';
                validate = false;
            }
            return validate;
        };

        $scope.foodNameChange = function () {
            if ($scope.food.foodName == undefined || $scope.food.foodName == '') {
                $scope.validate.div.foodName = '';
                $scope.validate.span.foodName = '';
                $scope.validate.help.foodName = '';
            } else {
                $scope.validate.div.foodName = $scope.validate.class.success;
                $scope.validate.span.foodName = $scope.validate.class.successGlyphicon;
                $scope.validate.help.foodName = '';
            }
        };

        $scope.foodPriceChange = function () {
            console.log($scope.food.foodPrice);
            if ($scope.food.foodPrice == undefined || $scope.food.foodPrice == '') {
                $scope.validate.div.foodPrice = '';
                $scope.validate.span.foodPrice = '';
                $scope.validate.help.foodPrice = '';
            } else {
                $scope.validate.div.foodPrice = $scope.validate.class.success;
                $scope.validate.span.foodPrice = $scope.validate.class.successGlyphicon;
                $scope.validate.help.foodPrice = '';
            }
        };

        $scope.foodTypeChange = function () {
            console.log($scope.food.foodType);
            $scope.validate.div.foodType = '';
            $scope.validate.help.foodType = '';
        };
        /* 前端校验 END */
    });

    //模态框对应的Controller
    app.controller('updModalCtrl', function ($scope, $rootScope, $modalInstance, $http, method, data, FileUploader) {

        $scope.hide = false;

        $scope.init = function () {
            $scope.title = '编辑菜品';
            $scope.food = data;
            $scope.method = method;
            $scope.types = $rootScope.types;
        };

        $scope.submit = function () {
            console.log("call upd modal submit()", $scope.data);
            if ($scope.validateCompletion()) {
                $http({
                    method: 'PUT',
                    url: 'foods',
                    data: $scope.food
                }).then(function successCallBack(res) {
                    console.log('callback upd modal submit() success', res);
                    $scope.method();
                    $modalInstance.close();
                }, function errCallback(res) {
                    console.log('callback upd modal submit() error', res);
                    alert("submit fail");
                });
            }
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };

        /* 上传图片 START*/

        // warnning using DOM
        $scope.browse = function () {
            document.getElementById('file').click();
        };

        // 上传控件
        $scope.uploader = new FileUploader({
            url: '/api/upload/foodpic',
            removeAfterUpload: true,
            queueLimit: 1
        });

        // 提交上传
        $scope.upload = function () {
            console.log("call upload");
            $scope.uploader.uploadAll();
        };

        // 上传完成执行此方�
        $scope.uploader.onCompleteItem = function (item, response, status, headers) {
            console.log("callback upload", response.path);
            $scope.food.foodPic = response.path;
            alert("上传成功");
        };
        /* 上传图片 END*/

        /* 前端校验 */
        $scope.validate = {
            class: {
                success: 'has-success has-feedback',
                warnning: 'has-warning has-feedback',
                error: 'has-error has-feedback',
                successGlyphicon: 'glyphicon glyphicon-ok form-control-feedback',
                warningGlyphicon: 'glyphicon glyphicon-warning-sign form-control-feedback',
                errorGlyphicon: 'glyphicon glyphicon-remove form-control-feedback'
            },
            div: {},
            span: {},
            help: {}
        };

        $scope.validateCompletion = function () {
            var validate = true;
            if ($scope.food.foodName == undefined || $scope.food.foodName == '') {
                $scope.validate.div.foodName = $scope.validate.class.error;
                $scope.validate.span.foodName = $scope.validate.class.errorGlyphicon;
                $scope.validate.help.foodName = '菜品名称不能为空';
                validate = false;
            }
            if ($scope.food.foodPrice == undefined || $scope.food.foodPrice == '') {
                $scope.validate.div.foodPrice = $scope.validate.class.error;
                $scope.validate.span.foodPrice = $scope.validate.class.errorGlyphicon;
                $scope.validate.help.foodPrice = '菜品价格不能为空';
                validate = false;
            }
            return validate;
        };

        $scope.foodNameChange = function () {
            if ($scope.food.foodName == undefined || $scope.food.foodName == '') {
                $scope.validate.div.foodName = '';
                $scope.validate.span.foodName = '';
                $scope.validate.help.foodName = '';
            } else {
                $scope.validate.div.foodName = $scope.validate.class.success;
                $scope.validate.span.foodName = $scope.validate.class.successGlyphicon;
                $scope.validate.help.foodName = '';
            }
        };

        $scope.foodPriceChange = function () {
            console.log($scope.food.foodPrice);
            if ($scope.food.foodPrice == undefined || $scope.food.foodPrice == '') {
                $scope.validate.div.foodPrice = '';
                $scope.validate.span.foodPrice = '';
                $scope.validate.help.foodPrice = '';
            } else {
                $scope.validate.div.foodPrice = $scope.validate.class.success;
                $scope.validate.span.foodPrice = $scope.validate.class.successGlyphicon;
                $scope.validate.help.foodPrice = '';
            }
        };
    });
};

/***/ }),
/* 5 */
/***/ (function(module, exports) {

module.exports = function (app) {
    app.controller('navCtrl', function ($scope, $rootScope) {
        $scope.searchf = function () {
            console.log("call search", $scope.search);
            $rootScope.search = $scope.search;
        };
    });
};

/***/ }),
/* 6 */
/***/ (function(module, exports) {

// app.factory('websocket', function ($websocket) {

//     // Open a WebSocket connection
//     var dataStream = $websocket('ws://localhost:3001/echo');

//     // var dataStream = $websocket('ws://localhost:3000/ws-stuff/echo');

//     var data = { msg: '', merchant: '' };

//     dataStream.onOpen(function () {
//         console.log('websocket onOpen');
//         dataStream.send('client: websocket open');
//     });

//     dataStream.onMessage(function (message) {
//         console.log('onMessage', message);
//         if (message.data == 'reflash') {
//             data.msg = '你有新的订单';
//         }
//     });

//     dataStream.onError(function () {
//         console.log('websocket onError');
//     });

//     dataStream.onClose(function () {
//         console.log('websocket onClose');
//     });

//     var methods = {
//         data: data,
//         setMerchant: function (merchant) {
//             dataStream.send({ merchant: merchant });
//         }
//         // get: function () {
//         //     dataStream.send(JSON.stringify({ action: 'get' }));
//         // }
//     };

//     return methods;
// });

// app.factory('socketio', function () {
//     var socket = io.connect('http://localhost:3001');
//     var methods = {
//         setMerchant: function (rootScope) {
//             socket.emit('id', { id: rootScope.merchant._id });
//             socket.on('update', function (data) {
//                 alert('您有新的订单，请及时处理');
//                 // 更新操作
//                 rootScope.hasNewOrder.boolean = true;
//                 rootScope.newOrder.number++;
//                 alert(rootScope.hasNewOrder.boolean);
//                 alert(rootScope.newOrder.number);
//             });
//         }
//     };
//     return methods;
// });
module.exports = function (app) {
    app.controller('orderCtrl', function ($scope, $rootScope, $http, socketio) {

        $scope.hasNewOrder = false;
        $scope.newOrder = 0;
        // socketio.setFunc(function (data) {
        //     alert('您有新的订单，请及时处理');
        //     // 更新操作
        //     $scope.hasNewOrder = true;
        //     $scope.newOrder++;
        //     alert($scope.hasNewOrder);
        //     alert($scope.newOrder);
        // });
        console.log('ffffffffffffff');
        console.log(window.updateFunc);
        console.log('ffffffffffffff');
        $scope.change = function () {
            $scope.hasNewOrder = true;
            $scope.newOrder++;
        };
        window.updateFunc = function (data) {
            alert('您有新的订单，请及时处理');
            // 更新操作
            $scope.change();
            $scope.$apply();
        };
        $scope.$watch('hasNewOrder', function () {
            console.log('bool change change');
        });
        $scope.$watch('newOrder', function () {
            console.log('number change change');
        });
        console.log('ffffffffffffff');
        console.log(window.updateFunc);
        console.log('ffffffffffffff');

        $scope.reflash = function () {
            $scope.sync();
        };

        $scope.orderByX = function (x) {
            console.log("call order by", x);
            $scope.orderBy = x;
        };
        $scope.init = function () {
            $scope.sync();
        };
        $scope.sync = function () {
            console.log("call orders sync()");
            $http({
                method: 'GET',
                url: 'orders'
            }).then(function successCallBack(res) {
                console.log('callback sync() success', res);
                $scope.orders = res.data;
            }, function errCallback(res) {
                console.log('callback sync() error', res);
            });
            $scope.hasNewOrder = false;
            $scope.newOrder = 0;
        };
    });
};

/***/ })
/******/ ]);